<template>
  <el-dialog
    v-model="dialogVisible"
    title="用户详情"
    width="900px"
    :close-on-click-modal="false"
    center
    destroy-on-close
    @closed="handleClosed"
  >
    <div v-if="user" class="user-detail">
      <!-- 用户基本信息卡片 -->
      <div class="detail-section">
        <div class="user-profile">
          <div class="profile-avatar">
            <el-avatar :size="80" :src="user.avatar">
              <el-icon size="40"><UserFilled /></el-icon>
            </el-avatar>
            <div class="status-badges">
              <el-tag v-if="user.isOnline" type="success" size="small" class="online-badge">
                <el-icon><Connection /></el-icon>
                在线
              </el-tag>
              <el-tag v-if="user.isVip" type="warning" size="small" class="vip-badge">
                <el-icon><Star /></el-icon>
                VIP
              </el-tag>
            </div>
          </div>
          <div class="profile-info">
            <h3 class="profile-name">{{ user.username }}</h3>
            <p class="profile-email">{{ user.email }}</p>
            <div class="profile-tags">
              <el-tag 
                v-for="role in user.roles" 
                :key="role.id"
                :type="getRoleTagType(role.code)"
                size="small"
              >
                {{ role.name }}
              </el-tag>
            </div>
          </div>
          <div class="profile-actions">
            <el-button type="primary" @click="handleEdit">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
          </div>
        </div>
      </div>

      <!-- 详细信息 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><InfoFilled /></el-icon>
          基本信息
        </h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="用户ID">{{ user.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="user.isActive ? 'success' : 'danger'">
              {{ user.isActive ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
          <!-- 部门字段已移除 -->
          <el-descriptions-item label="注册时间">{{ formatDate(user.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="登录次数">{{ user.loginCount || 0 }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 登录统计 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><DataAnalysis /></el-icon>
          登录统计
        </h3>
        <el-row :gutter="20" class="login-stats">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ user.loginCount || 0 }}</div>
              <div class="stat-label">总登录次数</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ getActiveDays() }}</div>
              <div class="stat-label">活跃天数</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ getLastActiveTime() }}</div>
              <div class="stat-label">最后活跃</div>
            </div>
          </el-col>
        </el-row>
        
        <div class="login-details">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="最后登录时间">
              {{ formatDate(user.lastLoginAt) || '从未登录' }}
            </el-descriptions-item>
            <el-descriptions-item label="最后登录IP">
              {{ user.lastLoginIp || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="注册IP">
              {{ user.registerIp || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="设备信息">
              {{ user.lastDevice || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 安全信息 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><Lock /></el-icon>
          安全信息
        </h3>
        <div class="security-items">
          <div class="security-item">
            <div class="security-icon">
              <el-icon><Key /></el-icon>
            </div>
            <div class="security-content">
              <div class="security-title">登录密码</div>
              <div class="security-desc">用于账号登录验证</div>
            </div>
            <div class="security-action">
              <el-button size="small" @click="handleResetPassword">
                {{ showPasswordForm ? '取消重置' : '重置密码' }}
              </el-button>
            </div>
          </div>
          
          <!-- 密码重置表单 - 下拉展开 -->
          <transition name="slide-down">
            <div v-if="showPasswordForm" class="password-reset-form">
              <div class="reset-form-header">
                <el-icon class="reset-icon"><Lock /></el-icon>
                <span>重置 {{ user?.username }} 的登录密码</span>
              </div>
              
              <el-form 
                ref="passwordFormRef"
                :model="passwordForm" 
                :rules="passwordFormRules" 
                label-width="80px"
                class="password-form"
              >
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    show-password
                    clearable
                    @input="checkPasswordStrength"
                  />
                  <div class="password-strength">
                    <div class="strength-bar">
                      <div 
                        class="strength-fill" 
                        :class="passwordStrength.level"
                        :style="{ width: passwordStrength.percent + '%' }"
                      ></div>
                    </div>
                    <span class="strength-text">{{ passwordStrength.text }}</span>
                  </div>
                </el-form-item>
                
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    placeholder="请再次输入新密码"
                    show-password
                    clearable
                  />
                </el-form-item>
                
                <el-form-item>
                  <div class="form-actions">
                    <el-button 
                      type="primary" 
                      @click="submitPasswordReset"
                      :loading="passwordResetLoading"
                    >
                      <el-icon><Check /></el-icon>
                      确认重置
                    </el-button>
                    <el-button @click="cancelPasswordReset">
                      <el-icon><Close /></el-icon>
                      取消
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </transition>
        </div>
      </div>

      <!-- 最近活动 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><Clock /></el-icon>
          最近活动
        </h3>
        <el-timeline>
          <el-timeline-item
            v-for="activity in recentActivities"
            :key="activity.id"
            :timestamp="activity.time"
            :type="getActivityType(activity.type)"
          >
            <div class="activity-item">
              <div class="activity-icon">
                <el-icon><component :is="getActivityIcon(activity.type)" /></el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-desc">{{ activity.description }}</div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑用户</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  UserFilled, Connection, Edit, ChatLineRound, InfoFilled,
  DataAnalysis, Lock, Key, Message, Clock, Star,
  Check, Close
} from '@element-plus/icons-vue'
import { formatDate } from '@/utils'
import { userApi } from '@/api/user'

const props = defineProps({
  visible: Boolean,
  user: Object
})

const emit = defineEmits(['update:visible', 'edit'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 密码重置相关状态
const showPasswordForm = ref(false)
const passwordResetLoading = ref(false)
const passwordFormRef = ref(null)
const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
})

// 密码强度检测
const passwordStrength = ref({
  level: 'weak',
  percent: 0,
  text: '请输入密码'
})

// 密码重置表单验证规则
const passwordFormRules = {
  newPassword: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 模拟最近活动数据
const recentActivities = ref([
  {
    id: 1,
    type: 'login',
    title: '用户登录',
    description: '从 192.168.1.100 登录系统',
    time: '2024-01-20 14:30:00'
  },
  {
    id: 2,
    type: 'profile',
    title: '更新资料',
    description: '修改了个人头像',
    time: '2024-01-19 10:15:00'
  },
  {
    id: 3,
    type: 'security',
    title: '密码变更',
    description: '用户主动修改登录密码',
    time: '2024-01-18 16:45:00'
  },
  {
    id: 4,
    type: 'system',
    title: '系统通知',
    description: '账号安全检查通过',
    time: '2024-01-17 09:20:00'
  }
])

const getRoleTagType = (code) => {
  const typeMap = {
    'super_admin': 'danger',
    'admin': 'warning', 
    'user': 'primary',
    'guest': 'info'
  }
  return typeMap[code] || 'primary'
}

const getActiveDays = () => {
  if (!props.user?.createdAt) return 0
  const created = new Date(props.user.createdAt)
  const now = new Date()
  const diffTime = Math.abs(now - created)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

const getLastActiveTime = () => {
  if (!props.user?.lastLoginAt) return '从未'
  const lastLogin = new Date(props.user.lastLoginAt)
  const now = new Date()
  const diffTime = Math.abs(now - lastLogin)
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
  
  if (diffHours < 1) return '刚刚'
  if (diffHours < 24) return `${diffHours}小时前`
  const diffDays = Math.floor(diffHours / 24)
  return `${diffDays}天前`
}

const getActivityType = (type) => {
  const typeMap = {
    'login': 'primary',
    'profile': 'success',
    'security': 'warning',
    'system': 'info'
  }
  return typeMap[type] || 'primary'
}

const getActivityIcon = (type) => {
  const iconMap = {
    'login': 'User',
    'profile': 'Edit',
    'security': 'Lock',
    'system': 'Setting'
  }
  return iconMap[type] || 'InfoFilled'
}

const handleEdit = () => {
  emit('edit', props.user)
  dialogVisible.value = false
}

const handleSendMessage = () => {
  ElMessage.info('发送消息功能开发中...')
}

const handleResetPassword = () => {
  if (showPasswordForm.value) {
    // 如果表单已展开，则收起
    showPasswordForm.value = false
  } else {
    // 展开表单
    showPasswordForm.value = true
    // 重置表单
    passwordForm.value = {
      newPassword: '',
      confirmPassword: ''
    }
    passwordStrength.value = {
      level: 'weak',
      percent: 0,
      text: '请输入密码'
    }
    // 清除表单验证
    setTimeout(() => {
      passwordFormRef.value?.clearValidate()
    }, 100)
  }
}

// 检测密码强度
const checkPasswordStrength = (password) => {
  if (!password) {
    passwordStrength.value = {
      level: 'weak',
      percent: 0,
      text: '请输入密码'
    }
    return
  }

  let score = 0
  let level = 'weak'
  let text = '弱'

  // 长度检查 (6-20位)
  if (password.length >= 6) score += 30
  if (password.length >= 8) score += 10
  if (password.length >= 12) score += 10

  // 字符类型检查 (必须包含字母和数字)
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasNumber = /\d/.test(password)
  const hasLowerCase = /[a-z]/.test(password)
  const hasUpperCase = /[A-Z]/.test(password)
  const hasSpecialChar = /[^A-Za-z0-9]/.test(password)

  // 基本要求：字母和数字
  if (hasLetter && hasNumber) {
    score += 20
  }

  // 额外加分项
  if (hasLowerCase) score += 5
  if (hasUpperCase) score += 5
  if (hasSpecialChar) score += 20

  // 根据分数确定强度
  if (score >= 70) {
    level = 'strong'
    text = '强'
  } else if (score >= 40) {
    level = 'medium'
    text = '中'
  }

  // 检查是否满足基本要求
  if (!hasLetter || !hasNumber) {
    level = 'weak'
    text = '必须包含字母和数字'
    score = Math.min(score, 30)
  } else if (password.length < 6) {
    level = 'weak'
    text = '密码长度至少6位'
    score = Math.min(score, 20)
  } else if (password.length > 20) {
    level = 'weak'
    text = '密码长度不超过20位'
    score = Math.min(score, 20)
  }

  passwordStrength.value = {
    level,
    percent: Math.min(score, 100),
    text: `密码强度: ${text}`
  }
}

// 提交密码重置
const submitPasswordReset = async () => {
  try {
    if (!passwordFormRef.value) return
    await passwordFormRef.value.validate()
    
    passwordResetLoading.value = true
    
    await userApi.resetPassword(props.user.id, {
      newPassword: passwordForm.value.newPassword
    })
    
    ElMessage.success(`用户 ${props.user.username} 的密码重置成功`)
    showPasswordForm.value = false
    
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('重置密码失败: ' + (error.response?.data?.message || error.message || '未知错误'))
  } finally {
    passwordResetLoading.value = false
  }
}

// 取消密码重置
const cancelPasswordReset = () => {
  showPasswordForm.value = false
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleClosed = () => {
  // 清理数据
}
</script>

<style scoped>
.user-detail {
  max-height: 65vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

.detail-section {
  margin-bottom: 32px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.user-profile {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.profile-avatar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.status-badges {
  display: flex;
  gap: 4px;
}

.online-badge {
  background: linear-gradient(45deg, #10b981, #059669);
  border: none;
  color: white;
  animation: pulse 2s infinite;
}

.vip-badge {
  background: linear-gradient(45deg, #fbbf24, #f59e0b);
  border: none;
  color: white;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.profile-info {
  flex: 1;
}

.profile-name {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.profile-email {
  color: #6b7280;
  font-size: 16px;
  margin: 0 0 12px 0;
}

.profile-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.profile-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  border-bottom: 2px solid #e5e7eb;
  padding-bottom: 8px;
}

.login-stats {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #4f46e5;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

.login-details {
  margin-top: 16px;
}

.security-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.security-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.security-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.security-content {
  flex: 1;
}

.security-title {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.security-desc {
  font-size: 14px;
  color: #6b7280;
}

.security-action {
  margin-left: auto;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin-top: 4px;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 14px;
  color: #6b7280;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条样式 */
.user-detail::-webkit-scrollbar {
  width: 6px;
}

.user-detail::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.user-detail::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.user-detail::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 描述列表样式 */
:deep(.el-descriptions__body) {
  background: #fafafa;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #374151;
  background: #f3f4f6 !important;
}

:deep(.el-descriptions__content) {
  color: #6b7280;
}

/* 时间线样式 */
:deep(.el-timeline-item__timestamp) {
  color: #9ca3af;
  font-size: 12px;
}

:deep(.el-timeline-item__content) {
  padding-left: 16px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-profile {
    flex-direction: column;
    text-align: center;
  }
  
  .profile-actions {
    flex-direction: row;
    justify-content: center;
  }
  
  .login-stats .el-col {
    margin-bottom: 16px;
  }
}

/* 密码重置表单样式 */
.password-reset-form {
  margin-top: 16px;
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  border-left: 4px solid var(--el-color-primary);
}

.reset-form-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.reset-form-header .reset-icon {
  color: var(--el-color-primary);
  font-size: 18px;
}

.password-form {
  margin-top: 16px;
}

.form-actions {
  display: flex;
  gap: 12px;
}

.form-actions .el-button {
  border-radius: 6px;
  font-weight: 500;
}

/* 下拉动画 */
.slide-down-enter-active {
  transition: all 0.3s ease-out;
}

.slide-down-leave-active {
  transition: all 0.2s ease-in;
}

.slide-down-enter-from {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.slide-down-leave-to {
  opacity: 0;
  transform: translateY(-5px);
  max-height: 0;
}

.slide-down-enter-to,
.slide-down-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 300px;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: #e5e7eb;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
  border-radius: 2px;
}

.strength-fill.weak {
  background: linear-gradient(90deg, #ef4444, #dc2626);
}

.strength-fill.medium {
  background: linear-gradient(90deg, #f59e0b, #d97706);
}

.strength-fill.strong {
  background: linear-gradient(90deg, #10b981, #059669);
}

.strength-text {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
  white-space: nowrap;
}

/* 确保对话框居中且无双滚动条 */
:deep(.el-dialog) {
  margin-top: 5vh !important;
  margin-bottom: 5vh !important;
  max-height: 90vh;
  overflow: visible;
  display: flex;
  flex-direction: column;
}

:deep(.el-dialog__header) {
  flex-shrink: 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
  overflow: visible;
  flex: 1;
  min-height: 0;
}

:deep(.el-dialog__footer) {
  flex-shrink: 0;
}
</style>
